package add

import (
	"fmt"
	"os"
	"regexp"
	"strings"

	"github.com/spf13/cobra"
	"golang.org/x/mod/modfile"
)

// CmdAdd represents the add command.
var CmdAdd = &cobra.Command{
	Use:   "add",
	Short: "Add a proto API template",
	Long:  "Add a proto API template. Example: sk-kratos add api/v1/hello.proto",
	Run:   run,
}

func run(cmd *cobra.Command, args []string) {
	// kratos proto add helloworld/v1/helloworld.proto
	input := args[0]
	n := strings.LastIndex(input, "/")
	if n == -1 {
		fmt.Println("The proto path needs to be hierarchical.")
		return
	}
	path := input[:n]
	fileName := input[n+1:]
	if !strings.HasSuffix(fileName, ".proto") {
		fileName += ".proto"
	}

	//pkgName := strings.ReplaceAll(path, "/", ".")
	nName := modName()
	li := strings.Split(nName, "/")
	domain := ""
	if len(li) > 1 && strings.HasSuffix(li[0], ".com") {
		nName = strings.Join(li[1:], "/")
		domain = li[0]
	}

	pkgName := strings.Replace(strings.Replace(nName, "/", ".", -1), "-", "_", -1)
	pkgName = pkgName + "." + strings.Replace(strings.Replace(path, "/", ".", -1), "-", "_", -1)
	gp := goPackage(path)
	gp = strings.Replace(gp, domain+"/", "", -1)
	p := &Proto{
		Name:      getFileNamePrefix(nName) + fileName,
		Path:      path,
		Package:   pkgName,
		GoPackage: gp,
		//		JavaPackage: javaPackage(pkgName),
		Service: serviceName(fileName),
	}
	if err := p.Generate(); err != nil {
		fmt.Println(err)
		return
	}
}

func modName() string {
	modBytes, err := os.ReadFile("go.mod")
	if err != nil {
		if modBytes, err = os.ReadFile("../go.mod"); err != nil {
			return ""
		}
	}
	return modfile.ModulePath(modBytes)
}

func goPackage(path string) string {
	s := strings.Split(path, "/")
	return modName() + "/" + path + ";" + s[len(s)-1]
}

func javaPackage(name string) string {
	return name
}

func phpPackage(name string) string {
	li := strings.Split(name, ";")
	name = li[0]
	li = strings.Split(name, "/")
	for k, v := range li {
		v = strings.Replace(v, "-", " ", -1)
		v = strings.Title(v)
		li[k] = strings.Replace(v, " ", "", -1)
	}
	return strings.Join(li, `\\`)
}

func serviceName(name string) string {
	return export(strings.Split(name, ".")[0])
}

func export(s string) string {
	s = strings.Replace(s, "_", " ", -1)
	s = strings.Title(s)
	s = strings.Replace(s, " ", "", -1)
	return s
}

func getFileNamePrefix(name string) string {
	li := strings.Split(name, "/")
	reg := regexp.MustCompile(`v[0-9]+`)
	sname := ""
	for i := len(li) - 1; i >= 0; i-- {
		if !reg.Match([]byte(li[i])) {
			sname = li[i]
			break
		}
	}
	return strings.Replace(sname, "-", "_", -1) + "_"
}
